package com.sgcc.pda.greendao.dao;

import android.content.Context;
import android.util.Log;

import com.sgcc.pda.baselibrary.application.HZBaseApplication;
import com.sgcc.pda.greendao.entity.DaoMaster;
import com.sgcc.pda.greendao.entity.DaoSession;

import org.greenrobot.greendao.database.Database;


/**
 * 数据库管理类.
 *
 * @author 王沛栋
 * @data 2017/12/26 09:57
 */

public class DBManager {
    //数据库名称
    public static final String DB_NAME = "marketData.db";
    private static final String DB_ENCRYP_PASD = "hzwq.888";

    private static DBManager instance = new DBManager();
    private DBOpenHelper mOpenHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    private Context mContext;
    private Database db;


    public static DBManager getInstance() {
//        if (instance == null) {
//            synchronized (DBManager.class) {
//                if (instance == null) {
//                    instance = new DBManager();
//                }
//            }
//        }
        return instance;
    }

    /**
     * 初始化
     */
    public void init(String dbPath) {
//        this.mContext = context;

        String fromPath = "/.platform/data/lib/libsqlcipher.so";
        System.load(fromPath);

        DaoMaster.OpenHelper helper = new DBOpenHelper(HZBaseApplication.getInstance(), dbPath);
        helper.setLoadSQLCipherNativeLibs(false);
//        Database db = helper.getWritableDb();
//        if (db != null) db.close();
        db = helper.getEncryptedWritableDb("hzwq.888");
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }

    /**
     * 获取对数据库的增删查找
     *
     * @return
     */
    public DaoSession getDaoSession() {
        return mDaoSession;
    }


    /**
     * 加密数据库
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        if (mOpenHelper == null) {
            mOpenHelper = new DBOpenHelper(mContext, DB_NAME, null);
            mOpenHelper.setLoadSQLCipherNativeLibs(false);
            String fromPath = "/.platform/data/lib/libsqlcipher.so";
            //String toPath = mContext.getFilesDir()+ File.separator+"libsqlcipher.so";
            try {
                System.load(fromPath);
                //使用加密方式
//                mDaoMaster = new DaoMaster(mOpenHelper.getEncryptedReadableDb(DB_ENCRYP_PASD));
                mDaoMaster = new DaoMaster(mOpenHelper.getWritableDb());

            } catch (RuntimeException e) {
                Log.e("load", "log", e);
                mDaoMaster = new DaoMaster(mOpenHelper.getWritableDb());
            } catch (UnsatisfiedLinkError e) {
                Log.e("load", "log", e);
                mDaoMaster = new DaoMaster(mOpenHelper.getWritableDb());
            }
        }
        return mDaoMaster;
    }


}
